<template>
  <div class="login">
    <h1 class="h1_position">欢迎登录神农-中医药服务平台</h1>
    <el-form ref="form" :model="form" label-width="80px" class="form">
      <el-form-item label="账号" >
        <el-input v-model="form.username" class="login-input"></el-input>
      </el-form-item>
      <el-form-item label="密码" >
        <el-input type="password" v-model="form.password" class="login-input"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading">
          <span v-if="!loading">登录</span>
          <span v-else> 正在登录,请稍后...</span>
        </el-button>
        <el-button @click="toRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '../api/login'

export default {
  name: 'Login',
  data() {
    return {
      loading: false,
      form: {
        username: '',
        password: ''
      }
    }
  },
  created() {
    let token = localStorage.getItem('Authorization');
    if (token != undefined) {
      this.$router.push('/');
    }
  },
  methods: {
    onSubmit() {
      this.loading = true;
      login(this.form).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          localStorage.setItem('Authorization', res.data.data.access_token);
          localStorage.setItem('token_expire', new Date().getTime()+3600*1000);
          localStorage.setItem('userInfo', JSON.stringify(res.data.data.userInfo));
          this.$message.success('登录成功！');
          this.loading = false;
          this.$router.replace('/index');
        } else {
          this.$message.error('账号或密码错误！');
        }
      });
    },
    // 点击跳转注册页面
    toRegister(){
      this.$router.replace('/register');
    }
  }
}
</script>

<style>
    .login{
      text-align: center;
      margin: auto;
      width: 100%;
      height: 100%;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      background: url(https://img.tukuppt.com/ad_preview/00/03/79/5c98b0f5175c7.jpg!/fw/980) no-repeat center;
      background-size: 100% 100%;
    }
    .h1_position{
      text-align: center;width: 50%;position: absolute;left: 50%;top: 25%;transform: translate(-50%,-50%)
    }
    .form{
      text-align: center;width: 50%;position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%)
    }
</style>